<template>
  <div class="user-management">
    <el-row :gutter="24">
      <el-col :span="2" class="actions">
        <el-button type="primary" @click="addUser">新增用户</el-button>
      </el-col>
    </el-row>

    <el-table
        :data="users"
        border
        stripe
        style="width: 100%"
        class="user-table"
    >
      <el-table-column prop="account" label="用户名" width="180">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180">
      </el-table-column>
      <el-table-column prop="password" label="密码" width="180">
      </el-table-column>
      <el-table-column prop="roleName" label="角色">
        <template #default="{ row }">
          <el-tag class="ml-2" type="warning">{{row.roleName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
      </el-table-column>
      <el-table-column prop="avatar" label="头像" width="180">
        <template #default="{ row }">
          <el-image
              :src="row.avatar"
              fit="cover"
              :lazy="true"
              style="width: 50px; height: 50px; border-radius: 10%; overflow: hidden; border: 2px solid var(--el-border-color); box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);"
              :preview-src-list="[row.avatar]"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button
              type="primary"
              plain
              size="small"
              @click="editUser(row)"
          >编辑</el-button
          >
          <el-button
              type="danger"
              plain
              size="small"
              @click="deleteUser(row.id)"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
        v-model="dialogVisible"
        :title="title"
        width="50%"
        center
        destroy-on-close
    >
      <el-form
          :model="userForm"
          ref="formRef"
          label-position="right"
          label-width="120px"
          class="form-container"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="userForm.account"
              autocomplete="off"
              placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
              v-model="userForm.email"
              autocomplete="off"
              placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleName">
          <el-select
              v-model="userForm.roleId"
              placeholder="请选择角色"
              size="small"
              @change="handleRoleChange"
          >
            <el-option
                v-for="item in roles"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="email">
          <el-input
              v-model="userForm.password"
              autocomplete="off"
              placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker
              v-model="userForm.createdAt"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择日期时间"
              size="small"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
              class="avatar-uploader"
              :headers="herders"
              :action="url"
              autocomplete="off"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="saveUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from '../../http/axios';
import {Plus} from "@element-plus/icons-vue";

// 用户数据类型
interface User {
  id: number;
  avatar: string;
  account: string;
  email: string;
  roleName: string;
  roleId:number;
  password: string;
  createdAt: string; // 更改为字符串类型
}
const title=ref('');
// 角色选项类型
interface RoleOption {
  id: string;
  roleName: string;
  description: string;
}
const url="/api/sys/user/uploadAvatar";
// 状态选项类型
interface StatusOption {
  value: string;
  label: string;
}
const herders = {
  authorization:''
};
const getToken=()=>{
  herders.authorization=localStorage.getItem("token");
};
// 用户列表
const users = ref<User[]>([]);
const handleRoleChange=(roleId)=>{
  userForm.value.roleId=roleId;
}
// 对话框可见性
const dialogVisible = ref(false);

// 表单数据
const userForm = ref<User>({
  id: 0,
  account: '',
  email: '',
  password: '',
  roleName: '',
  roleId:0,
  createdAt: '', // 初始化为空字符串
  avatar: ''
});

// 表单引用
const formRef = ref(null);

// 角色选项
const roles = ref<RoleOption[]>([]);

// 状态选项
const statusOptions = ref<StatusOption[]>([
  { value: 'active', label: '激活' },
  { value: 'inactive', label: '未激活' },
]);

// 加载用户数据
const loadUsers = async () => {
  try {
    const response = await axios.get('/sys/user/list');
    users.value = response.data.data;
    console.log(users.value);
  } catch (error) {
    console.error(error);
  }
}
//文件上传函数
// 添加新用户
const addUser = () => {
  title.value='添加用户';
  userForm.value = {
    id: 0,
    account: '',
    email: '',
    password: '',
    roleName: '',
    roleId:undefined,
    createdAt: '',
    avatar: ''
  };
  dialogVisible.value = true;
};

// 编辑用户
const editUser = (user: User) => {
  title.value='编辑用户';
  userForm.value = { ...user };
  dialogVisible.value = true;
};
//取消
const cancel = () => {
  dialogVisible.value = false;
  formRef.value.resetFields();
};
// 保存用户
const saveUser =() => {
  const user=userForm.value;
  try {
    if (userForm.value.id === 0) {
      axios.post('/sys/user/add', user).then((response) => {
        if (response.data.code === 200){
          loadUsers();
          location.reload();
          ElMessage.success('添加成功');
        }else {
          ElMessage.error(response.data.message);
        }
      })
    } else {
      console.log("form",user)
      updateRole(userForm.value)
    }
    dialogVisible.value = false;
  } catch (error) {
    console.error(error);
  }
};

// 删除用户
const deleteUser = async (id: number) => {
  console.log(id)
  await ElMessageBox.confirm(
      '此操作将永久删除该用户, 是否继续?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  );
  try {
    const response =await axios.delete(`/sys/user/delete/${id}`);
    if (response.data.code === 200){
      loadUsers();
      location.reload();
      ElMessage.success('删除成功');
    }else {
      location.reload();
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    console.error(error);
  }
};

// 更新角色
const updateRole = (user: User) => {
  axios.post('/sys/user/update', user)
      .then((response) => {
        if (response.data.code === 200){
          loadUsers();
          location.reload();
          ElMessage.success('更新成功');
        }else {
          location.reload();
          ElMessage.error(response.data.message);
        }
      }).catch((e) => {
        console.log(e);
      })
};
// 查询所有角色列表
const getAllRoles = async function () {
  try {
    const response = await axios.get('/sys/role/list');
    roles.value = response.data.data;
  } catch (error) {
    console.error(error);
  }
};
// 头像上传成功后的处理
const handleAvatarSuccess = (res: any, file: any) => {
  userForm.value.avatar = res.data;
};

// 上传前的验证
const beforeAvatarUpload = (file: any) => {
  const isJPG = file.type === 'image/jpeg';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};

// 在组件挂载完成后加载数据
onMounted(() => {
  loadUsers();
  getAllRoles();
  getToken();
});
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
}

.actions {
  text-align: right;
}

.user-table {
  margin-top: 20px;
}

.role-select {
  width: 100%;
}

.form-container {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
/* Ensure styles apply to el-dialog */
:deep(.el-dialog) {
  position: fixed !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  max-width: 90% !important;
  max-height: 80vh !important;
}

/* Center the dialog body content */
:deep(.el-dialog__body) {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

/* Ensure the dialog header is centered */
:deep(.el-dialog__header) {
  text-align: center;
}

:deep(.el-dialog__body .el-form) {
  width: 100%;
}

:deep(.el-dialog__body .el-form-item) {
  margin-bottom: 20px; /* Adjust space between form items */
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>